package com.flashflexpro.flexdirector.agent.scriptrunner {
import com.flashflexpro.flexdirector.agent.console.Console;

import flash.display.Loader;
import flash.events.Event;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.system.System;
import flash.utils.ByteArray;
import flash.utils.Dictionary;


public class ScriptRunner extends ScriptRunnerImpl{

    private static var _procedure2runner:Dictionary = new Dictionary();
    public static var currentProcedure:IUsingScriptRunner;
    public static function get procedure2runner():Dictionary{
        return _procedure2runner;
    }


    private static var _inst:ScriptRunner;
    public static function get inst():ScriptRunner{
        return _inst;
    }

    private static var _testCaseId:String;
    public static function get testCaseId():String{
        return _testCaseId;
    }

    public static function loadAndRunBuiltIn( tcId:String ):void {
        _testCaseId = tcId;
        runTCwhenLoaded();
    }

    public static function loadAndRunBinary( ba:ByteArray, tcId:String ):void {
        _testCaseId = tcId;
        var tmpLoader:Loader = new Loader();

        var onSwfLoaded:Function = function(ev:Event):void {
            tmpLoader.contentLoaderInfo.removeEventListener(Event.COMPLETE, onSwfLoaded);
            tmpLoader = null;
            runTCwhenLoaded();
        };

        tmpLoader.contentLoaderInfo.addEventListener(Event.COMPLETE, onSwfLoaded);
        tmpLoader.loadBytes(ba, new LoaderContext(false, ApplicationDomain.currentDomain));
    }

    private static function runTCwhenLoaded():void{
        var entryClassDef:* = ApplicationDomain.currentDomain.getDefinition(
                "com.flashflexpro.flexdirector.generated::" + _testCaseId );
        _inst = new ScriptRunner();
        var tmp:IUsingScriptRunner = new entryClassDef( _inst, null ) as IUsingScriptRunner;
        Console.inst.begin();
        _inst.runProcedure( tmp );

    }


    override public function exit():void {
        super.exit();
    }
}
}